package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/natefinch/lumberjack"
)

var (
	// Set during go build
	version   string
	gitCommit string
	buildTime string

	// 命令行参数
	logPath = flag.String("f", "", "file path")

	maxSize   = flag.Int("max.size", 10, "单位MB")
	maxBackup = flag.Int("max.backup", 60, "保留旧文件的最大个数.")
	maxAge    = flag.Int("max.age", 30, "保留旧文件的最大天数,单位（天）")
)

func getLogWriter(log string) *lumberjack.Logger {
	/*
		Filename: 日志文件的位置
		MaxSize：在进行切割之前，日志文件的最大大小（以MB为单位）
		MaxBackups：保留旧文件的最大个数
		MaxAges：保留旧文件的最大天数
		Compress：是否压缩/归档旧文件
	*/
	lumberJackLogger := &lumberjack.Logger{
		Filename:   log,
		MaxSize:    *maxSize,
		MaxBackups: *maxBackup,
		MaxAge:     *maxAge,
		LocalTime:  true,
		Compress:   true,
	}
	return lumberJackLogger
}

func main() {
	versionFlag := flag.Bool("version", false, "print the version")
	flag.Parse()
	// 版本打印
	if *versionFlag {
		fmt.Printf("Version: %s\n", version)
		fmt.Printf("Commit: %s\n", gitCommit)
		fmt.Printf("BuildTime: %s\n", buildTime)
		os.Exit(0)
	}

	if len(*logPath) == 0 {
		log.Fatal("Not file path.")
		return
	}

	fileInfo, _ := os.Stdin.Stat()
	if (fileInfo.Mode() & os.ModeNamedPipe) != os.ModeNamedPipe {
		log.Fatal("The command is intended to work with pipes.")
	}

	logger := getLogWriter(*logPath)
	defer logger.Close()
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		logger.Write(s.Bytes())
		logger.Write([]byte("\n"))
	}
}
